package com.vallis.lotteryonline.controller;


import com.alibaba.fastjson.JSONObject;
import com.vallis.lotteryonline.annotation.JwtIgnore;
import com.vallis.lotteryonline.entity.Audience;
import com.vallis.lotteryonline.entity.PayDetail;
import com.vallis.lotteryonline.entity.User;
import com.vallis.lotteryonline.filter.JwtInterceptor;
import com.vallis.lotteryonline.service.PayDetailService;
import com.vallis.lotteryonline.service.UserService;
import com.vallis.lotteryonline.util.CommonUtil;
import com.vallis.lotteryonline.util.HttpInvoker;
import com.vallis.lotteryonline.util.JwtTokenUtil;
import com.vallis.lotteryonline.util.Result;
import net.bytebuddy.utility.RandomString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author vallis
 * @since 2020-07-14
 */
@Controller
@RequestMapping("/pay-detail/")
public class PayDetailController {  //商户号
    private static String mchid = "";

    private static String key = "";

    @Autowired
    CommonUtil commonUtil;

    @Autowired
    PayDetailService payDetailService;

    @Autowired
    UserService userService;

    /**
     * 获取二维码支付地址
     */
    @PostMapping(value = "scanPay")
    public @ResponseBody Result scanPay(@RequestParam Map<String, String> params) {

        Map<String, String> userMap = JwtInterceptor.userMap;
        Map<String, String> map = new HashMap<>();
        //分
        String money = "1";
        map.put("mchid", mchid);
        map.put("total_fee", "" + money);
        //订单号
        map.put("out_trade_no", "valis"+commonUtil.convertDateString(new Date()));
        //用户自定义数据，在notify的时候会原样返回  uuid
        map.put("attach", userMap.get("id"));
        //回调地址
        map.put("notify_url", "https://payjs.cn/help/");//请注意，，该路径需要payjs服务器可以直接访问，且结果为200。测试地址不行，www.baidu.com也不行
        String md5 = commonUtil.sign(map, key);
        map.put("sign", md5.toUpperCase());
        // map.put("body", map.get("body"));
        // map.put("notify_url", map.get("notify_url"));
        String result = HttpInvoker.readContentFromPost("https://payjs.cn/api/native", map);
        JSONObject jsonObject = JSONObject.parseObject(result);
        // 1 请求成功 0请求失败
        if (null != jsonObject && "1".equals(jsonObject.getString("return_code"))) {
//            Map<String, String> maporder = new HashMap<>();
//            maporder.put("out_trade_no", "1111");
//            maporder.put("user_id", "1111");
             return  Result.ok(jsonObject.getString("qrcode"));
        } else if (null != jsonObject && "0".equals(jsonObject.getString("return_code"))) {
            return   Result.error(jsonObject.getString("return_msg"));
        }
        return Result.error("无数据");
    }

    /**
     * 二维码生成
     */
//    @PostMapping(value = "qrCode")
//    public void qrCode(HttpServletRequest request, HttpServletResponse response) {
//        String content = "姓名:十二余\n博客：https://www.cnblogs.com/jing5464";
//        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
//        // 指定编码格式
//        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
//        // 指定纠错级别(L--7%,M--15%,Q--25%,H--30%)
//        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
//        // 编码内容,编码类型(这里指定为二维码),生成图片宽度,生成图片高度,设置参数
//        BitMatrix bitMatrix = null;
//        try {
//            bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, 200, 200, hints);
//            //设置请求头
//            response.setHeader("Content-Type", "application/octet-stream");
//            response.setHeader("Content-Disposition", "attachment;filename=" + "十二余的二维码.png");
//            OutputStream outputStream = response.getOutputStream();
//            MatrixToImageWriter.writeToStream(bitMatrix, "png", outputStream);
//            outputStream.flush();
//            outputStream.close();
//        } catch (Exception e) {
//
//        }
//    }
    @PostMapping(value = "qrCode")
    public @ResponseBody
    void qrCode(@RequestParam("content") String content, HttpServletResponse response) {
        BufferedImage image;
        // 禁止图像缓存
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        image = commonUtil.createImage(content);
        // 创建二进制的输出流
        try (ServletOutputStream sos = response.getOutputStream()) {
            // 将图像输出到Servlet输出流中。
            ImageIO.write(image, "jpeg", sos);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @PostMapping(value = "notify")
    @JwtIgnore
    public @ResponseBody Result  notify(Integer return_code, Integer total_fee,
                               String out_trade_no, String payjs_order_id, String transaction_id, String time_end,
                               String openid, String mchid, String sign, String attach) {
        System.out.println("收到通知-----");
        PayDetail payDetail = new PayDetail();
        payDetail.setOpenid(openid);
        payDetail.setPayjsOrderId(payjs_order_id);
        payDetail.setReturnCode(return_code);
        payDetail.setTimeEnd(time_end);
        payDetail.setType("WetChat");
        payDetail.setTotalFee(total_fee);
        payDetail.setTransactionId(transaction_id);
        payDetail.setOutTradeNo(out_trade_no);
        if (return_code == 1) {
            User user = userService.getById(attach);
            user.setOutTradeNo(out_trade_no);
            user.setUserPayAmont(user.getUserPayAmont() + total_fee);
            payDetail.setUserPhone(user.getUserPhone());
            payDetail.setInsertDate(LocalDateTime.now());
            payDetailService.save(payDetail);
            userService.updateById(user);
        }else{
            return Result.error();
        }

        return Result.ok();
    }
}
